/**
 * NutchProcessDestroyer.java created at 2009-3-6
 * Copyrights Reserved. 2006
 */
package org.apache.nutch.web;

import java.util.Enumeration;
import java.util.Vector;

import org.apache.commons.exec.ProcessDestroyer;

/**
 * 
 * 
 * @author yanky
 */
public class NutchProcessDestroyer implements ProcessDestroyer, NutchListener {

	private Vector processes = new Vector();

	public NutchProcessDestroyer() {
	}

	public boolean add(Process process) {
		synchronized (processes) {
			processes.addElement(process);
			return processes.contains(process);
		}
	}

	public boolean remove(Process process) {
		synchronized (processes) {
			return processes.removeElement(process);
		}
	}

	public int size() {
		return processes.size();
	}

	public void statusUpdate(NutchEvent e) {
		String status = (String) e.getSource();
		if (status.equalsIgnoreCase("stop")) {
			synchronized (processes) {
				Enumeration en = processes.elements();
				while (en.hasMoreElements()) {
					Process process = (Process) en.nextElement();
					try {
						process.destroy();
					} catch (Throwable t) {
						System.err
								.println("Unable to terminate process during process shutdown");
					} finally {
						processes.remove(process);
						processes = null;
					}
					System.out.println("nutch stopped: " + process);
				}
			}
		}
	}

}
